from flask import Blueprint, request, render_template
from house.models import House
import math

# 创建蓝图对象
list_page = Blueprint('list_page', __name__)

# 定义过滤器
def deal_title_over(word):
    if len(word) > 15:
        return word[:15] + '...'
    else:
        return word

def deal_direction(word):
    if len(word) == 0 or word is None:
        return '暂无信息！'
    else:
        return word

# 注册过滤器
list_page.add_app_template_filter(deal_title_over, 'dealover')
list_page.add_app_template_filter(deal_direction, 'dealdirection')

@list_page.route('/query')
def search_txt_info():
    # 获取 addr 字段的查询结果
    if request.args.get('addr'):
        addr = request.args.get('addr')
        result = House.query.filter(House.address == addr).order_by(House.publish_time.desc()).all()
        return render_template('search_list.html', house_list=result)

    # 获取 rooms 字段的查询结果
    if request.args.get('rooms'):
        rooms_info = request.args.get('rooms')
        result = House.query.filter(House.rooms == rooms_info).order_by(House.publish_time.desc()).all()
        return render_template('search_list.html', house_list=result)

    return "没有搜索条件", 400

# 最新房源列表页
@list_page.route('/list/pattern/<int:page>')
def return_new_list(page):
    # 获取房源数据总量
    house_num = House.query.count()
    # 计算总的页码数，向上取整
    total_num = math.ceil(house_num / 10)
    # 按发布时间降序排列，并进行分页（每页10条）
    result = House.query.order_by(House.publish_time.desc()).paginate(page, per_page=10, error_out=False)
    return render_template('list.html',
                         house_list=result.items,
                         page_num=result.page,
                         total_num=total_num,
                         list_type='new')

# 热点房源列表页
@list_page.route('/list/hot_house/<int:page>')
def return_hot_list(page):
    # 获取房源数据总量
    house_num = House.query.count()
    # 计算总的页码数，向上取整
    total_num = math.ceil(house_num / 10)
    # 按浏览量降序排列，并进行分页（每页10条）
    result = House.query.order_by(House.page_views.desc()).paginate(page, per_page=10, error_out=False)
    return render_template('list.html',
                         house_list=result.items,
                         page_num=result.page,
                         total_num=total_num,
                         list_type='hot')